#!/usr/bin/python3
# -*- coding: utf8 -*-
# Date   : 2021/06/27
# Author : Kwan
# Email  : allenxian@live.com
# Blog   : https://my.oschina.net/u/4173440

from project.flasky import db
from project.define import db_logger


DataName = "识别相机"
TableName = "app_device_camera"


class DeviceCamera(db.Model):
    """
    识别相机信息
    """
    __tablename__ = 'app_device_camera'
    # 相机ID
    CameraID = db.Column(db.Integer, primary_key=True, autoincrement=True, nullable=False)
    # 闸机名称
    GateID = db.Column(db.String(16), nullable=False)
    # 闸机名称
    GateName = db.Column(db.String(16), nullable=False)
    # 对应车型
    VehicleType = db.Column(db.String(16), nullable=False)
    # 相机地址
    CamAddr = db.Column(db.String(32), nullable=False, unique=True)
    # Web端口
    WebPort = db.Column(db.Integer, nullable=False)
    # SDK端口
    SDKPort = db.Column(db.Integer, nullable=False)
    # 用户名
    UserName = db.Column(db.String(32), nullable=False)
    # 登录密码
    Password = db.Column(db.String(32), nullable=False)
    # 序列号
    Serial = db.Column(db.String(32))

    def __init__(self, **kwargs) -> None:
        super().__init__()
        self.GateID = kwargs.get('GateID')
        self.GateName = kwargs.get('GateName')
        self.VehicleType = kwargs.get('VehicleType')
        self.CamAddr = kwargs.get('CamAddr')
        self.WebPort = kwargs.get('WebPort')
        self.SDKPort = kwargs.get('SDKPort')
        self.UserName = kwargs.get('UserName')
        self.Password = kwargs.get('Password')

    def to_dict(self):
        """
        转换键值对
        """
        return dict([(c.name, getattr(self, c.name)) for c in self.__table__.columns])

    @staticmethod
    def current_datas():
        """
        当前闸机
        """
        cameras = DeviceCamera.query.all()
        if cameras:
            return [i.to_dict() for i in cameras]
        return []

    @staticmethod
    def selected_data(**kwargs):
        """
        选中数据
        """
        camera_id = kwargs.get('CameraID')
        if camera_id:
            return DeviceCamera.query.filter_by(CameraID=camera_id).first()

    @staticmethod
    def columns_name():
        """
        数据表标题
        """
        ColumnName = {
            'CameraID': '相機ID', 'GateID':'車場閘機','GateName': '閘機名稱', 'VehicleType': '地感車型','CamAddr': '相機地址', 
            'WebPort':'Web端口', 'SDKPort':'SDK端口', 'UserName': '用戶名', 'Password': '登錄密碼', 'Serial': '序列號'
            }
        return ColumnName

    @staticmethod
    def generate_filters(**kwargs):
        """
        筛选器
        """
        filters = set()
        for k, v in kwargs.items():
            if v:
                if hasattr(DeviceCamera, k):
                    if k == 'GateName':
                        filters.add(DeviceCamera.GateName == v)
                    elif k == 'VehicleType':
                        filters.add(DeviceCamera.VehicleType == v)
        return filters

    @staticmethod
    def insert_data(**kwargs):
        """
        新增
        """
        try:
            r = DeviceCamera(**kwargs)
            db.session.add(r)
            db.session.commit()
            db_logger.debug(f"{TableName} => 新增{DataName}成功：{kwargs}")
            return r.to_dict()
        except Exception as e:
            db.session.rollback()
            db_logger.error(f"{TableName} => 新增{DataName}失败：{kwargs} 原因：{e}")

    @staticmethod
    def delete_data(**kwargs):
        """
        删除
        """
        try:
            r = DeviceCamera.selected_data(**kwargs)
            if r:
                db.session.delete(r)
                db.session.commit()
                db_logger.debug(f"{TableName} => 删除{DataName}D成功：{kwargs}")
                return r.to_dict()
        except Exception as e:
            db.session.rollback()
            db_logger.error(f"{TableName} => 删除{DataName}失败：{kwargs} 原因：{e}")

    @staticmethod
    def modify_data(**kwargs):
        """
        修改
        """
        try:
            update = False
            r = DeviceCamera.selected_data(**kwargs)
            if r:
                for k, v in kwargs.items():
                    if hasattr(r, k):
                        if getattr(r, k) != v:
                            setattr(r, k, v)
                            update = True
                if update:
                    try:
                        db.session.commit()
                        db_logger.debug(f"{TableName} => 更新{DataName}成功：{kwargs}")
                        return r.to_dict()
                    except Exception as e:
                        db.session.rollback()
                        db_logger.error(f"{TableName} => 更新{DataName}失败：{kwargs} 原因：{e}")
                else:
                    return "ignore"
        except Exception as e:
            db_logger.error(f"{TableName} => 更新{DataName}参数错误：{kwargs} 原因：{e}")


    @staticmethod
    def table_init(*args):
        """
        数据初始化
        """
        demo_data = {
            'Entrance':[
                {'VehicleType':'Moto','CamAddr':'192.168.0.30'},
                {'VehicleType':'Car','CamAddr':'192.168.0.31'},
                ],
            'Exit':[
                {'VehicleType':'Moto','CamAddr':'192.168.0.32'},
                {'VehicleType':'Car','CamAddr':'192.168.0.33'},
                ],
        }
        for g in args:
            if isinstance(g, dict):
                gate_type = g.get('GateType')
                cam = demo_data.get(gate_type)
                if cam:
                    for c in cam:
                        cam_addr = c.get('CamAddr')
                        if cam_addr:
                            r = DeviceCamera.query.filter_by(CamAddr=cam_addr).first()
                            if not r:
                                c.update(**{'WebPort':8000, 'SDKPort':3000, 'UserName': 'admin', 'Password': '123456'})
                                g.update(**c)
                                DeviceCamera.insert_data(**g)
